<?php
/**
 * Created by WXCH
 * Date: 2020/1/8 0008 18:32
 */
namespace app\api\service;

use app\api\model\Product as ProductModel;
use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\model\UserAddress;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;
use think\Db;
use think\Exception;

/**
 * 订单类
 * 1. 创建订单
 * 2. 支付前
 * 3. 支付成功
 */
class Order{
    protected $product_id;
    protected $product;
    protected $uid;

    function __construct(){}

    /**
     * @param int $uid 用户id
     * @param array $oProducts 订单商品列表
     * @return array 订单商品状态
     * @throws Exception
     */
    public function place($uid, $product_id){
        $this->product_id = $product_id;
        $this->product = $this->getProductById($product_id);
        $this->uid = $uid;
        //创建订单
        try {
            $orderSnap = $this->snapOrder();

            $orderNo = $this->makeOrderNo();
            $order = new OrderModel();
            $time1 = time();

            $order->user_id = $this->uid;
            $order->product_id = $this->product_id;
            $order->order_no = $orderNo;
            $order->price = $this->product['price'];
            $order->snap_thumb = $this->product['thumb'];
            $order->snap_name = $this->product['name'];
            $order->snap_fakenum = $this->product['fakenum'];
            $order->create_time = $time1;
            $res = $order->save();
            $orderID = $order->id;
            $create_time = $order->create_time;
            if($res){
                return [
                    'status' => 0,
                    'order_no' => $orderNo,
                    'order_id' => $orderID,
                    'create_time' => $create_time
                ];
            }else{
                return [
                    'status' => -1
                ];
            }

        } catch (Exception $ex) {
            throw $ex;
        }
    }

    // 生成订单快照
    private function snapOrder(){
        // status可以单独定义一个类
        $snap = [
            'price' => $this->product['price'],
            'snapName' => $this->product['name'],
            'snapThumb' => $this->product['thumb'],
            'fakenum' => $this->product['fakenum']
        ];
        return $snap;
    }

    // 根据订单查找真实商品
    private function getProductById($product_id){
        return ProductModel::get($product_id);
    }

    private static function makeOrderNo(){
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }
}